package designPatterns.com.course_design.scrapy.logger;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @projectName DesignPattern
 * @className com.course_design.scrapy.logger.Logger
 * @description
 */

public class ConcreteLogger implements Log {
    public static void main(String[] args) {
        Log log = new ConcreteLogger(ConcreteLogger.class);
        log.info("打印一条日志");
    }

    public ConcreteLogger(Class<?> clz){
        this.className = clz.getSimpleName();
    }
    final static SimpleDateFormat format = new SimpleDateFormat("yyyy:MM:dd-HH:mm:ss");
    private String className;

    @Override
    public void info(Object o) {
        String method = Thread.currentThread().getStackTrace()[2].getMethodName();
        this.createLogInfo(o,method,INFO);
    }

    @Override
    public void warn(Object o) {
        String method = Thread.currentThread().getStackTrace()[2].getMethodName();
        this.createLogInfo(o,method,WARN);
    }

    @Override
    public void debug(Object o) {
        String method = Thread.currentThread().getStackTrace()[2].getMethodName();
        this.createLogInfo(o,method,DEBUG);
    }

    @Override
    public void error(Object o) {
        String method = Thread.currentThread().getStackTrace()[2].getMethodName();
        this.createLogInfo(o,method,ERROR);
    }

    @Override
    public void fatal(Object o) {
        String method = Thread.currentThread().getStackTrace()[2].getMethodName();
        this.createLogInfo(o,method,FATAL);
    }

    private void createLogInfo(Object o,String method,String level){
        StringBuilder sb = new StringBuilder();
        //日期
        Date date = new Date();
        sb.append(format.format(date));
        sb.append(" [")
                .append(level)
                .append("]: ")
                .append(this.className)
                .append(".")
                .append(method)
                .append(" ");
        sb.append(o.toString())
                .append('\n');
        System.out.print(sb);
        writeLog(sb.toString());
    }

    private void writeLog(String msg){
        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\scrapy_log.txt";
        try {
            Writer writer = new FileWriter(path,true);
            writer.write(msg);
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
